<?php
/**
 * @since      File available since Release v1.1
 */
defined('Inbearshop') or exit('Access Invalid!');
define('MYSQL_RESULT_TYPE',1);
class oauthControl extends Control{
	public function __construct(){
		parent::__construct();
        Language::read('indexs');
        Tpl::output('index_sign','index');
	}
	
	
	public function getcodeOp(){
		$code = $_GET['code'];
		$state = $_GET['state'];
		$refurl = $_GET['refurl'];

		if(empty($refurl)){
			$refurl = BASE_SITE_URL;
		}else{
			$refurl = str_replace('|','&',$refurl);
		}
		
		$refurl = htmlspecialchars_decode($refurl);
		
		$model = Model();
		$wxaccount = $model->table('wxaccount')->where(array('wx_id'=>1))->find();
		
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wxaccount['wx_appid']}&secret={$wxaccount['wx_appsecret']}&code={$code}&grant_type=authorization_code";
		$jsoninfo = $this->getdata($url);
		
		$user = array();
		$user['openid'] = $jsoninfo['openid'];
		
		$userinfo = $model->table('user')->where($user)->find();
		if(!empty($userinfo)){
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$jsoninfo['access_token']}&openid={$userinfo['openid']}";
			$memberinfo = $this->getdata($url);
			
			$update = array();
			$update['avatar'] = $memberinfo['headimgurl'];
			$update['nickname'] = $memberinfo['nickname'];

			$data = $this->getUserInfo($user['openid']);
			$update = array_merge($update,$data);
			
			$model->table('user')->where(array('user_id'=>$userinfo['user_id']))->update($update);
			//$_SESSION['user_id'] = $userinfo['user_id'];
			setcookie('user_id',$userinfo['user_id'], time()+3600);
			header("Location:{$refurl}");	
			exit;
		}else{
			$user['access_token'] = $jsoninfo['access_token'];
			$res = $model->table('user')->insert($user,true);
			if($res){
				$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$user['access_token']}&openid={$user['openid']}";
				$memberinfo = $this->getdata($url);
					
				$update = array();
				$update['avatar'] = $memberinfo['headimgurl'];
				$update['nickname'] = $memberinfo['nickname'];
				
				$data = $this->getUserInfo($user['openid']);
				$update = array_merge($update,$data);
				
				$model->table('user')->where(array('user_id'=>$res))->update($update);
				//$_SESSION['user_id'] = $userinfo['user_id'];
				setcookie('user_id',$userinfo['user_id'], time()+3600);
				
				header("Location:{$refurl}");
				exit;	
			}else{
				exit;
			}
		}
	}
	

	
	public function getdata($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		$jsoninfo = json_decode($output, true);
		
		return $jsoninfo;
	}

}